package rpg.data;

import java.io.File;

import org.jdom.Element;

import pedrosm.data.ScriptData;
import pedrosm.utils.Debug;

import square.data.DataGroup;
import square.data.EffectData;
import square.data.SpriteData;
import square.script.EffectScript;

/**
 * 
 * @author Pedro Silva Moreira
 */
public class EffectXML implements LoaderXML {
	private static EffectXML singleton = new EffectXML();
	
	// Creation
	private EffectXML() {
	}
	
	// Instance
	public static EffectXML instance() {
		return singleton;
	}
	
	// Load
	@SuppressWarnings("unchecked")
	public void load(String group, String name, Element origin) {
		Element elem = XML.loadXML(XML.DATA_FOLDER + "effects" + File.separator
				+ group + File.separator + name + ".xml");

		EffectData data = new EffectData();
		
		// Group
		data.setGroup(group);
		
		// Name
		data.setName(elem.getAttributeValue("name"));

		// Time
		String time = elem.getAttributeValue("time");
		if (time != null)
			data.setTime(Integer.valueOf(time));

		// Sprite
		String spriteName = elem.getAttributeValue("sprite");
		if (spriteName != null) {
			SpriteData sprite = DataGroup.findSprite(spriteName);
			if (sprite == null) {
				Debug.debug("EffectXML", "Failed to create EffectData with sprite: "
						+ elem.getAttributeValue("sprite"));
				return;
			}
			data.setSprite(sprite);
		}

		// Script
		String script = elem.getAttributeValue("script");
		if (script != null) {
			data.setScript((ScriptData<EffectScript>) DataGroup.findScript(script));
		}

		DataGroup.getEffects().add(data);
	}
}
